package com.like.miaosha.access;

import com.alibaba.fastjson.JSON;
import com.like.miaosha.domain.MiaoshaUser;
import com.like.miaosha.redis.AccessKey;
import com.like.miaosha.redis.RedisService;
import com.like.miaosha.result.CodeMsg;
import com.like.miaosha.result.Result;
import com.like.miaosha.service.MiaoshaUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * @ClassName AccessInterceptor
 * @Description: TODO
 * @Author dongfengke
 * @Date 2022/1/18
 * @Version V1.0
 **/

@Service
public class AccessInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    MiaoshaUserService miaoshaUserService;

    @Autowired
    RedisService redisService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            MiaoshaUser user = getUser(request, response);
            UserContext.setUser(user);
            HandlerMethod hm=(HandlerMethod) handler;
            AccessLimit accessLimit = hm.getMethodAnnotation(AccessLimit.class);
            if(accessLimit==null) return true;

            int seconds= accessLimit.seconds();
            int maxCount=accessLimit.maxCount();
            boolean needLogin= accessLimit.needLogin();
            String key =request.getRequestURI();
            if(needLogin){
                if(user==null){
                    render(response,CodeMsg.SESSION_ERROR);
                    return false;
                }
                key+="_"+user.getId();
            }
            else{
                //do_nothing
            }
            AccessKey ak=AccessKey.withExpire(seconds);
            Integer count=redisService.get(ak,key,Integer.class);
            if(count==null){
                redisService.set(ak,key,1);
            }else if(count<5){
                redisService.incr(ak,key);
            }else {
                render(response,CodeMsg.ACCESS_LIMIT);
                return false;
            }
        }
        return true;

    }

    private void render(HttpServletResponse resp,CodeMsg codeMsg) throws Exception{
        resp.setContentType("application/json;charset=UTF-8");
        OutputStream out =resp.getOutputStream();
        String str= JSON.toJSONString(Result.error(codeMsg));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }

    private MiaoshaUser getUser(HttpServletRequest request,HttpServletResponse response){
        String paramToken=request.getParameter(MiaoshaUserService.COOKIE_NAME_TOKEN);
        String cookieToken=getCookieValue(request,MiaoshaUserService.COOKIE_NAME_TOKEN);
        if(StringUtils.isEmpty(cookieToken)&&StringUtils.isEmpty(paramToken)){
            return null;
        }
        String token =StringUtils.isEmpty(paramToken)?cookieToken:paramToken;
        return miaoshaUserService.getByToken(response,token);
    }
    private String getCookieValue(HttpServletRequest request, String cookieNameToken) {
        Cookie[]cookies=request.getCookies();
        if(cookies==null||cookies.length==0) return null;
        for (Cookie cookie : cookies) {
            if(cookie.getName().equals(cookieNameToken))
                return cookie.getValue();
        }
        return null;
    }
}
